﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace DusonFramework.Documents.PDF.itextsharp
{
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System.Text.RegularExpressions;

    class Example
    {
        public void Test1()
        {
            string content = ""; // 内容
            Document document1 = new Document();
            PdfWriter.GetInstance(document1, new FileStream(@"PDF保存路径", FileMode.Create));
            document1.Open();

            List<iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(content), null);

            #region 方法1

            //for (int k = 0; k < htmlarraylist.Count; k++)
            //{
            //    document1.Add((IElement)htmlarraylist[k]);
            //}

            #endregion

            #region 方法2

            //定义字体
            BaseFont b1 = BaseFont.CreateFont(@"Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font f = new Font(b1, 12);

            Paragraph mypara = new Paragraph("", f);
            mypara.InsertRange(0, htmlarraylist);
            document1.Add(mypara);

            #endregion

            document1.Close();
        }

        /// <summary>
        /// 转为PDF
        /// </summary>
        public void Test2()
        {
            //设置页面大小
            Rectangle pageSize = PageSize.A4;
            //创建文档对象
            Document document = new Document(pageSize);
            PdfWriter.GetInstance(document, new FileStream("Pdf保存路径", FileMode.Create));

            //打开文档
            document.Open();

            //定义字体
            BaseFont bfSongTi = BaseFont.CreateFont(@"Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfSongTi, 12);

            //定义字体
            BaseFont bfSongTiBlod = BaseFont.CreateFont(@"Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font fontBlod = new Font(bfSongTiBlod, 15);

            //提示段落
            Paragraph pToop = new Paragraph(new Chunk("本文档由程序整理生成（生成时间：" + DateTime.Now + "）", fontBlod));
            //1为居中，0为居左，2为居右
            pToop.Alignment = 1;
            pToop.SpacingAfter = 20;
            document.Add(pToop);

            //标题
            Paragraph pTitle = new Paragraph(new Phrase("标题", fontBlod));
            pTitle.Alignment = 1;
            pTitle.SpacingAfter = 20;
            document.Add(pTitle);

            //添加子标题
            Paragraph pDescription = new Paragraph("子标题", font);
            pDescription.Alignment = 0;

            //行间距（倍）
            pDescription.MultipliedLeading = 2;
            pDescription.SpacingAfter = 20;
            document.Add(pDescription);

            //内容
            Paragraph blogContent;

            //提取图片
            string Content = "";
            Regex reg = new Regex(@"(?is)(?:<img[^>]*?src|\bbackground)=(?:(['""])(?<img>[^'"">]+)\1|(?<img>[^'""\s>]+))");
            MatchCollection mc;
            IList<string> picList;

            //内容处理
            Content = Content.Replace("<p>", "卍");
            Content = Content.Replace("<br />", "卍");
            Content = Content.Replace("<br/ />", "卍");

            mc = reg.Matches(Content);
            picList = new List<string>();
            for (int i = 0; i < mc.Count; i++)
            {
                Match m = mc[i];
                if (!m.Groups["img"].Value.Contains("OutliningIndicators"))
                {
                    picList.Add(m.Groups["img"].Value);
                    Content = Content.Replace(m.Groups["img"].Value, "\" />卍Pic" + m.Groups["img"].Value + "ciP卍<img src=\"");
                }
            }

            //去掉Html标签
            Content = NoHTML(Content);

            //按内容生成段落
            string[] ContentArray = Content.Split('卍');
            for (int i = 0; i < ContentArray.Length; i++)
            {
                for (int j = 0; j < picList.Count; j++)
                {
                    if (ContentArray[i] == "Pic" + picList[j] + "ciP")
                    {
                        Image jpeg = Image.GetInstance(picList[j]);
                        if (jpeg.Width > PageSize.A4.Width)
                        {
                            jpeg.ScaleAbsolute(PageSize.A4.Width, jpeg.Width * jpeg.Height / PageSize.A4.Width);
                        }
                        jpeg.Alignment = Image.MIDDLE_ALIGN;
                        document.Add(jpeg);
                        ContentArray[i] = "PicDRJciP";
                    }
                }
                if (ContentArray[i] != "PicDRJciP")
                {
                    blogContent = new Paragraph(ContentArray[i], font);
                    blogContent.Alignment = 0;
                    blogContent.MultipliedLeading = 2;
                    blogContent.SpacingAfter = 10;
                    document.Add(blogContent);
                }
            }

            //提示信息
            Paragraph drj = new Paragraph(new Chunk("", font));
            //1为居中，0为居左，2为居右
            drj.Alignment = 1;
            drj.SpacingAfter = 20;
            drj.SpacingBefore = 20;
            document.Add(drj);

            //关闭文档
            document.Close();
        }

        /// <summary>
        /// 去掉HTML标签
        /// </summary>
        /// <param name="Htmlstring">带有HTML标签的字符串</param>
        /// <returns>string</returns>
        private string NoHTML(string Htmlstring)
        {
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");

            return Htmlstring.Trim();
        }

    }
}
